package com.example.himalayaproject.find.recommend.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.himalayaproject.R;
import com.example.himalayaproject.find.recommend.Recommend_Serviece.RecommendService;
import com.example.himalayaproject.find.recommend.adapter.RecommendAdapter;
import com.example.himalayaproject.find.recommend.bean.Entity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class RecommendFragment extends Fragment implements Callback<Entity> {


    private RecommendAdapter adapter;

    private SwipeRefreshLayout fresh;

    public RecommendFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_recommend, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        fresh = ((SwipeRefreshLayout) view.findViewById(R.id.layout_swipe_refresh));
        onFresh();
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recommend_frg);
        adapter = new RecommendAdapter(getContext());
        RecommendService service = new Retrofit.Builder()
                .baseUrl("http://mobile.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(RecommendService.class);
        service.getHotRecommends().enqueue(this);
        recyclerView.setAdapter(adapter);
    }

    //添加下拉刷新操作
    private void onFresh() {
        fresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                adapter.notifyDataSetChanged();
                fresh.setRefreshing(false);
            }
        });
    }

    @Override
    public void onResponse(Call<Entity> call, Response<Entity> response) {
        adapter.addAll(response.body().getHotRecommends().getList());
        adapter.addAlls(response.body().getGuess().getList());
        //  Log.d("1620", response.body().getHotRecommends().getList().get(0).getTitle());
    }

    @Override
    public void onFailure(Call<Entity> call, Throwable t) {
        t.printStackTrace();
        //Toast.makeText(this.getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        // Log.d("1620", t.getMessage());
    }
}
